import personInfo from "@/views/wy-lessor/landlord/components/person-info.vue";
import employeeInfo from "@/views/wy-lessor/landlord/components/employee-info.vue";
import uploadMedia from "@/components/upload-media.vue";
import { getDivision } from "@/admin/api/division";
import { getDictAndPlease } from "~/utils";
import {
    getObj,
    addObj,
    putObj,
    getClientLesseeByCardId
} from "@/views/wy-lessor/landlord/api/lessor";
import { validatePhone, validateEmail, validateIdNo } from "~/utils/validate";
export default {
    components: {
        personInfo,
        uploadMedia,
        employeeInfo
    },
    computed: {
        detailAddress() {
            const { provinceCode, cityCode, countyCode } = this.propForm;
            let province = this.provinces.find(
                item => item.value == provinceCode
            );
            let city = this.citys.find(item => item.value == cityCode);
            let county = this.countys.find(item => item.value == countyCode);
            return `${province ? province.label : ""} ${
                city ? city.label : ""
            } ${county ? county.label : ""}`;
        },
        selectProvice() {
            return this.provinces.find(
                p => p.value == this.propForm.provinceCode
            );
        },
        selectCity() {
            return this.citys.find(p => p.value == this.propForm.cityCode);
        },
        selectCounty() {
            return this.countys.find(p => p.value == this.propForm.countyCode);
        },
        chArea() {
            let p = this.selectProvice ? this.selectProvice.label : "";
            let c = this.selectCity ? this.selectCity.label : "";
            let y = this.selectCounty ? this.selectCounty.label : "";
            return p + c + y;
        }
    },
    props: {},
    data() {
        var validateCertificateNum = (rule, value, callback) => {
            if (!value) {
                callback();
            }
            this.validateCertificateNumOnly(value, callback);
        };
        return {
            propForm: {
                lessorId: "",
                lessorName: "",
                lessorType: "",
                certificateType: ""
            },
            originalCertificateNum: "",
            optionVal: "",
            uploadFileList: [],
            modelType: "client-manage",
            rules: {
                lessorName: [
                    {
                        required: true,
                        message: "请输入出租方名称",
                        trigger: "blur"
                    }
                ],
                lessorType: [
                    {
                        required: true,
                        message: "请选择出租方类型",
                        trigger: "blur"
                    }
                ],
                certificateType: [
                    {
                        required: true,
                        message: "请选择证件类型",
                        trigger: "blur"
                    }
                ],
                workUnit: [],
                certificateNum: [
                    {
                        required: true,
                        message: "请输入证件号码",
                        trigger: "blur"
                    },
                    { validator: validateCertificateNum, trigger: "change" }
                ],
                categroyEmployment: [],
                registerFund: [],
                unitNature: [],
                primaryBusiness: [],
                phoneNum: [
                    {
                        required: true,
                        message: "请输入手机号码",
                        trigger: "blur"
                    },
                    { validator: validatePhone, trigger: "change" }
                ],
                email: [
                    {
                        required: true,
                        message: "请输入电子邮件",
                        trigger: "blur"
                    },
                    { validator: validateEmail, trigger: "blur" }
                ],
                legalPerson: [],
                legalIdentityCard: [
                    { validator: validateIdNo, trigger: "change" }
                ],
                telephone: [],
                provinceCode: [],
                cityCode: [],
                countyCode: [],
                address: [],
                introduceUnit: [],
                remarks: [
                    {
                        min: 0,
                        max: 100,
                        message: "长度在0-100个字符串",
                        trigger: "blur"
                    }
                ]
            },
            editPersons: [],
            delPersons: [],
            provinces: [],
            citys: [],
            countys: [],
            isAdd: true,
            busId: "",
            url: "/admin/sys-file/upLodeFileAdd",
            fileSize: 50,
            idEdit: false,
            lesseeOptions: [],
            lesseeOptionsCopy: [],
            certificateOptions: [],
            certificateOptionsCopy: []
        };
    },
    created() {
        if (this.isAdd) {
            this.queryProvince();
            this.initClientLesseeType();
        }
        //获取传递过来的url参数
        this.propForm.lessorId = this.$route.query.id;

        if (this.propForm.lessorId) {
            //根据url参数查询一条数据
            this.isEdit = true;
            this.url = "/admin/sys-file/upLodeFileEdit";
            this.initCitySelector();
        } else {
        }
    },
    mounted() {},
    methods: {
        handleTotalPrices() {
            var regPos = /^\d+(\.\d+)?$/;
            if (!regPos.test(this.propForm.registerFund)) {
                this.$message.error("注册资金不能小于0且不能包含特殊字符！");
            }
        },

        // 修改时初始化地址选择器
        async initCitySelector() {
            this.busId = this.propForm.lessorId;
            // this.$refs.loadFiles.getFiles(this.busId)
            await getObj(this.propForm.lessorId).then(rep => {
                this.isAdd = false;
                this.propForm = rep.data.data;
                //将客户类型转化为字符串，结合下拉列表
                this.propForm.lessorType += "";
                this.optionVal = this.propForm.lessorType;
                this.originalCertificateNum = this.propForm.certificateNum;
                //获取省市县区下拉数据
                this.queryProvince();
                if (this.propForm.provinceCode) {
                    this.queryCitys(this.propForm.provinceCode);
                }
                if (this.propForm.cityCode) {
                    this.queryCounty(this.propForm.cityCode);
                }

                this.initClientLesseeType();
                if (this.propForm.lessorType) {
                    this.queryCertificateType();
                }
            });
            this.$refs.loadFiles.getFiles(this.busId);
        },
        //验证证件号唯一
        validateCertificateNumOnly(value, callback) {
            let certificateType = this.propForm.certificateType;
            let lessorType = this.propForm.lessorType;
            if (certificateType === "01") {
                var reg = new RegExp(
                    "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)"
                );
                if (value === "" || value === undefined || value == null) {
                    callback();
                } else {
                    if (!reg.test(value) && value !== "") {
                        callback(new Error("请输入正确的身份证号码"));
                    }
                }
            } else if (certificateType === "02") {
                var reg = new RegExp(
                    "^[\u4E00-\u9FA5]{1,2}(字第)([0-9a-zA-Z]{4,8})(号?)$"
                );
                if (value === "" || value === undefined || value == null) {
                    callback();
                } else {
                    if (!reg.test(value) && value !== "") {
                        callback(new Error("请输入正确的军官证号码"));
                    }
                }
            } else if (certificateType === "03") {
                reg = new RegExp("^[HMhm]{1}([0-9]{10}|[0-9]{8})$");
                if (value === "" || value === undefined || value == null) {
                    callback();
                } else {
                    if (!reg.test(value) && value !== "") {
                        callback(new Error("请输入正确的港澳台证号码"));
                    }
                }
            } else if (certificateType === "04") {
                reg = new RegExp(
                    "^([EeKkGgDdSsPpHh]d{8}$)|(^(([Ee][a-fA-F])|([DdSsPp][Ee])|([Kk][Jj])|([Mm][Aa])|(1[45]))d{7}$)"
                );
                if (value === "" || value === undefined || value == null) {
                    callback();
                } else {
                    if (!reg.test(value) && value !== "") {
                        callback(new Error("请输入正确的护照号码"));
                    }
                }
            } else if (certificateType === "05") {
                callback();
            }

            if (!this.originalCertificateNum === this.propForm.certificateNum) {
                getClientLesseeByCardId({
                    lessorType: lessorType,
                    certificateType: certificateType,
                    certificateNum: value
                }).then(resp => {
                    console.log(resp.data, "getClientLesseeByCardId");
                    let data = resp.data;
                    if (data.length != 0) {
                        return callback(
                            new Error("校验失败，该证件号码已经存在 ！")
                        );
                    } else {
                        callback();
                    }
                });
            } else {
                callback();
            }
        },
        //监听省市区下拉
        handleSelectChange(value, type) {
            const { provinceCode, cityCode, countyCode } = this.propForm;
            const province = this.provinces.find(
                item => item.value == provinceCode
            );
            const city = this.citys.find(item => item.value == cityCode);
            const county = this.countys.find(item => item.value == countyCode);
            this.propForm.address = `${province ? province.label : ""} ${
                city ? city.label : ""
            } ${county ? county.label : ""}`;
            const methods = {
                provinces: "queryCitys",
                citys: "queryCounty"
            };
            type !== "countys" && this[methods[type]](value);
        },
        queryProvince() {
            getDivision({ lazy: true, parentId: "000000" }).then(rep => {
                let rep_province = rep.data.data;
                this.provinces = rep_province.map(p => {
                    return { label: p.divisionName, value: p.divisionCode };
                });
            });
        },
        //获取城市
        queryCitys(val) {
            getDivision({ lazy: true, parentId: val }).then(rep => {
                let rep_city = rep.data.data;
                this.citys = rep_city.map(p => {
                    return { label: p.divisionName, value: p.divisionCode };
                });
            });
        },
        //获取县区
        queryCounty(val) {
            getDivision({ lazy: true, parentId: val }).then(rep => {
                let rep_county = rep.data.data;
                this.countys = rep_county.map(p => {
                    return { label: p.divisionName, value: p.divisionCode };
                });
            });
        },
        //初始化承租方类型
        initClientLesseeType() {
            this.lesseeOptions = getDictAndPlease("lessee_type");
            this.lesseeOptionsCopy = this.lesseeOptions;
        },
        //点击承租方类型下拉列表后，查询对应的证件类型
        queryCertificateType() {
            if (this.propForm.lessorType == 0) {
                this.certificateOptions = getDictAndPlease(
                    "personage_certificate_type"
                );
                this.certificateOptionsCopy = this.certificateOptions;
            } else {
                this.certificateOptions = getDictAndPlease(
                    "commercial_certificate_type"
                );
                this.certificateOptionsCopy = this.certificateOptions;
            }
        },
        commit() {
            this.$refs.propForm.validate(valid => {
                if (
                    valid &&
                    this.$refs[
                        this.propForm.lessorType == "0" ? "info1" : "info2"
                    ].formVerify
                ) {
                    this.uploadFileList.length > 0
                        ? this.$refs.loadFiles.submit(
                              this.modelType,
                              this.propForm.lessorId
                          )
                        : this.submitForm();
                }
            });
        },
        submit() {
            if (this.propForm.lessorType == "0") {
                this.$refs.info1.check();
            } else if (this.propForm.lessorType != "0") {
                this.$refs.info2.check();
            }
        },
        submitForm(val) {
            this.propForm.areaCode =
                this.propForm.provinceCode +
                this.propForm.cityCode +
                this.countryCode;
            for (var i = 0; i < this.editPersons.length; i++) {
                this.editPersons[i].lessorId = val;
            }
            this.$refs.propForm.validate(valid => {
                if (valid) {
                    if (this.propForm.lessorId) {
                        let editPersons = this.$refs.info1.editPersons;
                        for (let i = 0; i < this.editPersons.length; i++) {
                            this.editPersons[
                                i
                            ].lessorId = this.propForm.lessorId;
                        }
                        let requestData = {
                            ...this.propForm,
                            clientLesseeLinkinfos: editPersons,
                            delClientLesseeLinkinfos: this.delPersons
                        };
                        putObj(requestData).then(rep => {
                            if (rep.data.code === 0) {
                                this.$store.commit(
                                    "delHistoryRoute",
                                    this.$route.fullPath
                                );
                                this.$router.go(-1);
                            } else {
                                this.$message.error("修改失败");
                            }
                        });
                    } else {
                        this.propForm.lessorId = val;
                        for (let i = 0; i < this.editPersons.length; i++) {
                            this.editPersons[
                                i
                            ].lessorId = this.propForm.lessorId;
                        }
                        addObj(
                            Object.assign({}, this.propForm, {
                                clientLesseeLinkinfos: this.editPersons
                            })
                        )
                            .then(rep => {
                                if (rep.data.code === 0) {
                                    this.$store.commit(
                                        "delHistoryRoute",
                                        this.$route.fullPath
                                    );
                                    this.$router.push(
                                        "/wy-lessor/lessor-manage"
                                    );
                                } else {
                                    this.$message.error("新增失败");
                                }
                            })
                            .catch(e => {
                                console.log(e);
                            });
                    }
                }
            });
        },
        beforeUpload() {
            // this.loadAction('请稍等...')
        },
        onSuccess(response, file, fileList) {
            if (response.data) {
                this.submitForm(response.data);
                this.$refs.loadFiles.getFiles(response.data);
            } else {
                this.err("提交失败");
            }
        },
        onError(err, file, fileList) {
            this.err("提交失败");
        },
        lesseeDataFilter(val) {
            this.formData.lessorType = val;
            if (val) {
                //val存在
                this.lesseeOptions = this.lesseeOptionsCopy.filter(item => {
                    if (
                        !!~item.label.indexOf(val) ||
                        !!~item.label.toUpperCase().indexOf(val.toUpperCase())
                    ) {
                        return true;
                    }
                });
            } else {
                //val为空时，还原数组
                this.lesseeOptions = this.lesseeOptionsCopy;
            }
        },
        certificateDataFilter(val) {
            this.formData.certificateType = val;
            if (val) {
                //val存在
                this.certificateOptions = this.certificateOptionsCopy.filter(
                    item => {
                        if (
                            !!~item.label.indexOf(val) ||
                            !!~item.label
                                .toUpperCase()
                                .indexOf(val.toUpperCase())
                        ) {
                            return true;
                        }
                    }
                );
            } else {
                //val为空时，还原数组
                this.certificateOptions = this.certificateOptionsCopy;
            }
        }
    }
};
